﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;
using Sealight.API.Framework;
using System.IO;
using System.Web.Routing;
using ImageDrawing = System.Drawing.Image;
using Sealight.UI.WebUI.UIHelpers;

namespace Sealight.UI.WebUI.Controllers.FileUpload
{
    public class FileController : Controller
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(FileController));

        #region Images
        //
        // GET: /Admin/Upload/
        [Authorize]
        public ActionResult Index()
        {
            ViewData["CKEditorFuncNum"] = Request.QueryString["CKEditorFuncNum"];
            ViewData["CKEditor"] = Request.QueryString["CKEditor"];
            ViewData["langCode"] = Request.QueryString["langCode"];

            var dirPath = Path.Combine(Server
            .MapPath("~/Content/Images/editors"));
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            string[] fileNames = Directory.GetFiles(dirPath);
            List<FileInfo> images = new List<FileInfo>();
            foreach (string filename in fileNames)
            {
                FileInfo image = new FileInfo(filename);
                images.Add(image);
            }
            return View(images);
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(HttpPostedFileBase file,
            string CKEditorFuncNum, string CKEditor, string langCode)
        {
            if (file.ContentLength > 0)
            {
                var dirPath = Path.Combine(Server
                .MapPath("~/Content/Images/editors"));
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(dirPath, fileName);
                file.SaveAs(path);
            }

            RouteValueDictionary rvd = new RouteValueDictionary();
            rvd.Add("CKEditorFuncNum", CKEditorFuncNum);
            rvd.Add("CKEditor", CKEditor);
            rvd.Add("langCode", langCode);

            return RedirectToAction("Index", rvd);
        }
        [Authorize]
        public ActionResult Images(string id)
        {
            // So that I don't need to specify another route.
            string filename = id;

            // Get image filename from Request object.             
            string photoFolder = Server.MapPath("~/Content/Images/editors");
            filename = Path.Combine(photoFolder, filename);
            int width = 150; int height = 150;
            string bg = "#ffffff";

            StreamReader r = new StreamReader(filename);
            ImageDrawing thumbnail = ImageDrawing.FromStream(r.BaseStream);

            MemoryStream ms = new MemoryStream();
            thumbnail =ImageObject.Scale(thumbnail, width, height, bg);
            thumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            byte[] imageByte = ms.ToArray();

            ms.Dispose();
            thumbnail.Dispose();
            r.Dispose();

            return File(imageByte, "image/jpeg");
        }

        #endregion


        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile()
        {
            string imageUrl = string.Empty;
            bool valid = true;

            AjaxOperationResponse response = new AjaxOperationResponse();
            if (Request.Files.Count > 0)
            {
                string ext = Path.GetExtension(Request.Files[0].FileName).ToLower();
                if (!string.IsNullOrEmpty(ext) && !UIHelpers.ImageObject.CheckExt(ext))
                {
                    response.OperationComplete = false;
                    response.ErrorCode = "4001";
                    response.ErrorFriendlyMessage = "Operation error.  ErrMsg: invalid file extension (jpg|png|jpeg|gif).";
                    valid = false;


                }
            }

            if (valid)
            {

                if (Request["folder"] != null)
                {
                    imageUrl = UIHelpers.ImageObject.SaveImage(System.Web.HttpContext.Current, Guid.NewGuid(), Request["folder"].ToString());
                }
                else
                {
                    imageUrl = UIHelpers.ImageObject.SaveImage(System.Web.HttpContext.Current, Guid.NewGuid());
                }

                return Content(imageUrl, "text/html");
            }
            else
            {                
                return Content("0", "text/html");
            }
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadDocument()
        {
            string fileUrl = string.Empty;
            string ext = string.Empty;
            bool valid = true;

            if (Request.Files.Count > 0)
            {
                ext = Path.GetExtension(Request.Files[0].FileName).ToLower();
            }

            if (valid)
            {
                Guid guid = Guid.NewGuid();

                if (Request["folder"] != null)
                {
                    fileUrl = UIHelpers.FileObject.SaveFile(System.Web.HttpContext.Current, Request.Files[0], Guid.NewGuid(), Request["folder"].ToString());
                }
                else
                {
                    fileUrl = UIHelpers.FileObject.SaveFile(System.Web.HttpContext.Current, Request.Files[0], Guid.NewGuid());
                }
               
                return Content(fileUrl, "text/html");
            }
            else
            {
                return Content("0", "text/html");
            }
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImageWithCKEditor(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            string url; // url to return
            string message; // message to display (optional)
            // path of the image
            string path = "Content/images";
            string imageName = string.Empty;
            
            if (Request["folder"] != null)
            {                
                imageName = UIHelpers.ImageObject.SaveImage(System.Web.HttpContext.Current, Guid.NewGuid(), Request["folder"].ToString());

                path = path + "/" + Request["folder"].ToString() + "/" + imageName;
            }
            else
            {
                imageName = UIHelpers.ImageObject.SaveImage(System.Web.HttpContext.Current, Guid.NewGuid());

                path = path + "/" + imageName;
            }          

            // will create <a href="http://localhost:1457/Content/Images/my_uploaded_image.jpg" rel="nofollow">http://localhost:1457/Content/Images/my_uploaded_image.jpg</a>
            url = Request.Url.GetLeftPart(UriPartial.Authority) + "/" + path;

            // passing message success/failure
            message = "Image was saved correctly";

            // since it is an ajax request it requires this string
            string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + message + "\");</script></body></html>";
            return Content(output);
        }
    }
}
